<template>
  <div class="main-content pd16">

    <!--搜索栏-->
    <el-form class="search-form" ref="searchFormRef" :model="searchForm" :inline="true" label-width="70">

      <el-form-item label="标题" prop="title" label-width="40">
        <el-input v-model="searchForm.title" placeholder="请输入" clearable style="width: 200px"
                  @keyup.enter="searchData"/>
      </el-form-item>
      <el-form-item label="内容" prop="content" label-width="40">
        <el-input v-model="searchForm.content" placeholder="请输入" clearable style="width: 200px"
                  @keyup.enter="searchData"/>
      </el-form-item>

      <el-form-item label="通知类型" prop="type" label-width="80">
        <el-select v-model="searchForm.type" placeholder="请选择" clearable style="width: 130px">
          <el-option v-for="dict in enu_sys_msg_read_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="通知范围" prop="readRange" label-width="80">
        <el-select v-model="searchForm.readRange" placeholder="请选择" clearable style="width: 130px">
          <el-option v-for="dict in enu_sys_msg_read_range" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="接收条件" prop="readLimit" label-width="80">
        <el-select v-model="searchForm.readLimit" placeholder="请选择" clearable style="width: 130px">
          <el-option v-for="dict in enu_sys_msg_read_limit" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="searchData">搜索</el-button>
        <el-button icon="Refresh" @click="resetSearch">重置</el-button>
      </el-form-item>

    </el-form>

    <!--按钮组-->
    <div class="fx mgb12">
      <el-button type="primary" plain size="small" icon="Plus" @click="openAdd">新增通知</el-button>
      <el-button type="danger" plain size="small" icon="Delete" @click="deleteBatch">批量删除</el-button>
    </div>

    <!--表格-->
    <el-table border highlight-current-row row-key="id" v-loading="option.loading" :data="option.tableData"
              @selection-change="selectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column label="标题" prop="title" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column label="内容" prop="content" :show-overflow-tooltip="true"></el-table-column>

      <el-table-column label="通知类型" align="center" prop="type" :show-overflow-tooltip="true" width="150">
        <template #default="scope">
          <dict-tag :options="enu_sys_msg_read_type" :value="scope.row.type"></dict-tag>
        </template>
      </el-table-column>

      <el-table-column label="通知范围" align="center" prop="readRange" :show-overflow-tooltip="true" width="150">
        <template #default="scope">
          <dict-tag :options="enu_sys_msg_read_range" :value="scope.row.readRange"></dict-tag>
        </template>
      </el-table-column>

      <el-table-column label="接收条件" align="center" prop="readLimit" :show-overflow-tooltip="true" width="150">
        <template #default="scope">
          <dict-tag :options="enu_sys_msg_read_limit" :value="scope.row.readLimit"></dict-tag>
        </template>
      </el-table-column>

      <el-table-column label="阅读量" align="center" prop="readCount" :show-overflow-tooltip="true" width="150">
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="ct" width="170"></el-table-column>
      <el-table-column label="发送时间" align="center" prop="ct" width="170"></el-table-column>
      <el-table-column label="操作" align="center" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="Edit">
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div class="fx_end">
      <el-pagination
          class="mgt8"
          small
          background
          :total="option.totalRow"
          :page-sizes="option.pageSizes"
          v-model:current-page="searchForm.pageNumber"
          v-model:page-size="searchForm.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="searchData"
          @current-change="searchData"
      />
    </div>

    <!--Dialog-->
    <el-dialog :title="option.dialogTitle" v-model="option.openDialog" width="680" :close-on-click-modal="false"
               draggable append-to-body destroy-on-close>

      <el-form ref="formDataRef" size="default" :model="formData" :rules="formRules" label-width="100">

        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入" style="width: 400px"/>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input
              v-model="formData.content"
              maxlength="500"
              placeholder="请输入"
              show-word-limit
              :autosize="{ minRows: 2, maxRows: 6 }"
              style="width: 400px"
              type="textarea"
          />
        </el-form-item>

        <el-form-item label="接收条件" prop="readLimit" v-if="!(formData.readRange=='3'|| formData.readRange=='4')">
          <!--          multiple-->
          <el-select v-model="formData.readLimit" collapse-tags
                     collapse-tags-tooltip
                     :max-collapse-tags="4" placeholder="请选择" style="width: 400px">
            <el-option v-for="dict in enu_sys_msg_read_limit" :key="dict.value" :label="dict.label"
                       :value="dict.value"/>
          </el-select>
        </el-form-item>

        <el-form-item label="通知类型" prop="type">
          <el-select v-model="formData.type" collapse-tags collapse-tags-tooltip
                     :max-collapse-tags="4" placeholder="请选择" style="width: 400px">
            <el-option v-for="dict in enu_sys_msg_read_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>

        <el-form-item label="通知范围" prop="readRange">
          <el-select v-model="formData.readRange" collapse-tags collapse-tags-tooltip
                     :max-collapse-tags="4" placeholder="请选择" style="width: 400px">
            <el-option v-for="dict in enu_sys_msg_read_range" :key="dict.value" :label="dict.label"
                       :value="dict.value"/>
          </el-select>
        </el-form-item>


        <el-form-item label="指定角色" prop="roleIds" v-if="formData.readRange=='1'">
          <el-select v-model="formData.roleIds" collapse-tags collapse-tags-tooltip multiple
                     :max-collapse-tags="4" placeholder="请选择" style="width: 400px">
            <el-option v-for="dict in enu_sys_send_role" :key="dict.value" :label="dict.label"
                       :value="dict.value"/>
          </el-select>
        </el-form-item>


        <el-form-item label="指定用户" prop="userIds" v-if="formData.readRange=='2'">
          <el-input v-model="formData.userIds" placeholder="TODO TODO" style="width: 400px"/>
        </el-form-item>

        <el-form-item label="引导文章" prop="articleName">
          <el-input v-model="formData.articleName" placeholder="TODO TODO" style="width: 400px"/>
        </el-form-item>


      </el-form>

      <template #footer>
        <el-button @click="()=>{option.openDialog=false}">取 消</el-button>
        <el-button v-if="option.dialogType==='add'" type="primary" @click="submitAdd">确 定</el-button>
      </template>

    </el-dialog>


  </div>
</template>

<script setup>
import {getCurrentInstance, onMounted, ref} from "vue";
import {apiAllMyCreateRole, apiSysMsgDelete, apiSysMsgInsert, apiSysMsgPageData, apiSysMsgReadAll,} from "@/api/system";
import $modal from "@/common/utils/modal";
import {copyNew} from "@/common/utils/kit";
import DictTag from "@/common/component/DictTag.vue";
import {asDict} from "@/api/common";

const {proxy} = getCurrentInstance();
const {
  enu_sys_msg_read_type,//系统通知-通知类型
  enu_sys_msg_read_range,//系统通知-通知范围
  enu_sys_msg_read_limit,//系统通知-接收条件
  enu_sys_send_role,//系统通知-角色下拉选
} = asDict("enu_sys_msg_read_type", "enu_sys_msg_read_range", "enu_sys_msg_read_limit", "enu_sys_send_role");

let optionKey = {
  loading: false,
  dialogType: "",
  dialogTitle: "",
  openDialog: false,
  tableData: [],
  selectIds: [],
  selectNames: [],
  pageSizes: [1, 10, 20, 50, 100],
  totalRow: 0,
  nowRoleId: 0,
  defaultChecked: [],
  allRole: [],
}
let formKey = {
  title: "",
  content: "",
  type: "0",
  readRange: "0",
  readLimit: "0",
}
let searchKey = {
  pageNumber: 1,
  pageSize: 10,
  // 相关搜索参数
  title: "",
  content: "",
  type: "",
  readRange: "",
  readLimit: "",
}

const formRules = ref({
  title: [{required: true, message: "不能为空", trigger: "blur"}],
  content: [{required: true, message: "不能为空", trigger: "blur"}],
  type: [{required: true, message: "不能为空", trigger: "change"}],
  readRange: [{required: true, message: "不能为空", trigger: "change"}],
  readLimit: [{required: true, message: "不能为空", trigger: "change"}],
  roleIds: [{required: true, message: "不能为空", trigger: "blur"}],
  userIds: [{required: true, message: "不能为空", trigger: "blur"}],
});

const searchForm = ref(searchKey)
const formData = ref(formKey);
const option = ref(optionKey);

function resetForm() {
  formData.value = copyNew(formKey);
}

function resetSearch() {
  proxy.$refs["searchFormRef"].resetFields();
}

//页面加载完成回调
onMounted(() => {

  searchData()

  apiAllMyCreateRole().then(res => {
    option.value.allRole = res.data
  })

})

function selectionChange(rows) {
  option.value.selectIds = rows.map(item => item.id);
  option.value.selectNames = rows.map(item => item.title);
}

//搜索数据
function searchData() {
  option.value.loading = true;
  apiSysMsgPageData(searchForm.value).then(res => {
    let {totalRow, records, pageNumber, pageSize} = res.data;
    option.value.loading = false;
    option.value.totalRow = totalRow * 1
    option.value.tableData = records
    searchForm.value.pageNumber = pageNumber * 1
    searchForm.value.pageSize = pageSize * 1
  })
}

function openAdd() {
  resetForm()
  option.value.dialogTitle = "新增通知";
  option.value.openDialog = true;
  option.value.dialogType = "add";
}

function submitAdd() {
  proxy.$refs["formDataRef"].validate(valid => {

    if (valid) {
      apiSysMsgInsert(formData.value).then(res => {
        if (res.success) {
          //console.log(res)
          $modal.success();
          option.value.openDialog = false;
          searchData()
        }
      })
    }

  });
}

function deleteBatch() {
  if (option.value.selectIds.length === 0) {
    $modal.warning("请至少选择一条数据");
    return;
  }

  //console.log(ids)
  let content = `正在删除名称为【 ${option.value.selectNames.join("、")}】 的数据项，是否确定删除？ `
  $modal.confirmWarning(content)
      .then(async () => {
        apiSysMsgDelete({ids: option.value.selectIds.join(",")}).then(res => {
          if (res.success) {
            $modal.success();
            searchData()
          }
        })
      }).catch(() => $modal.cancel());
}

function read() {
  if (option.value.selectIds.length === 0) {
    $modal.warning("请至少选择一条数据");
    return;
  }
  //console.log(ids)
  let content = `将以下通知设为已读【 ${option.value.selectNames.join("、")}】 ，是否继续操作？ `
  $modal.confirmWarning(content)
      .then(async () => {

      }).catch(() => $modal.cancel());
}

function readAll() {
  let content = `全部已读，是否继续操作  `
  $modal.confirmWarning(content)
      .then(({value}) => {
        apiSysMsgReadAll().then(res => {
          if (res.success) {
            $modal.success();
          }
        })
      })
      .catch(() => {
      })
}

</script>

<style scoped lang="less">

</style>